/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.TimeUnit;

/**
 * <p>Project: javase - T14
 * <p>Powered by webrx On 2021-12-27 11:11:53
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class T14 {
    Object lock = new Object();
    List<String> list = new ArrayList<>();

    void add() {
        String t = Thread.currentThread().getName();
        System.out.println(t + "增加线程启动...");
        for (int i = 0; i < 6; i++) {
            synchronized (this) {
                synchronized (lock) {
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    String item = "Item" + list.size();
                    list.add(item);
                    System.out.println(t + ":增加" + item);
                    if (list.size() == 6) {
                        try {
                            lock.notify();
                            lock.wait();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

    }

    void count() {
        String t = Thread.currentThread().getName();
        System.out.println(t + "统计线程启动...");
        synchronized (lock) {
            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(t + ":容器到6个元素了.");
            System.out.println(t + ":监控线程结束...");
            lock.notify();
        }
    }

    public static void main(String[] args) {
        var t = new T14();

        new Thread(t::add, "Add1").start();
        new Thread(t::add, "Add2").start();
        new Thread(t::add, "Add3").start();
        new Thread(t::add, "Add4").start();
        new Thread(t::add, "Add5").start();
        new Thread(t::add, "Add6").start();
        new Thread(t::count, "Count").start();
    }
}
